<?php

class AlipayController extends MController
{
	public function actionRespond()
	{
		//$this->model('test', 'test', 'id')->insert(array('post' => json_encode($_REQUEST)));
		$notify_data = !empty($_REQUEST['notify_data']) ? $_REQUEST['notify_data'] : '';
		
		//$res = $this->model('test', 'test', 'id')->findByPk(25);
		//$r = json_decode($res['post'], true);
		//$notify_data = $r['notify_data'];
		
		
		if (!empty($notify_data)) {
			$notify_data = simplexml_load_string($notify_data);
			if ($notify_data->trade_status == 'TRADE_FINISHED') {
				// 支付订单固定格式 UID_时间戳_购买类型_(其余参数,看具体类型)
				// 购买类型:
				// 		1. 股权购买 (_项目ID_购买数量_每份价格_购买总价)
				//		2. 订阅购买 (_目标ID_订阅时长ID_价格)

				list($data['uid'], $data['ordernum']) = explode('_', $notify_data->out_trade_no);
				$data['howmuch'] = floatval($notify_data->price) * 10;
				$data['createtime'] = time();
				$data['paytype'] = '支付宝';
				if ($this->model('Financedetail')->isExist($data['uid'], $data['ordernum']) === false) {
					$this->model('Financedetail')->insert($data);
					$this->model('UserMoney')->addMoney($data['uid'], $data['howmuch']);
					$this->model('consume')->insert(array(
						'userid' => $data['uid'],
						'itemid' => 0,
						'howmuch' => $data['howmuch'],
						'createtime' => time(),
						'sorpuserid' => 0,
						'consumetype' => 4
					));
					echo '1';die;
				}
			}
		} else {
			if ($_REQUEST['trade_status'] == 'TRADE_SUCCESS') {
				list($data['uid'], $data['ordernum']) = explode('_', $_REQUEST['out_trade_no']);
				$data['howmuch'] = floatval($_REQUEST['price']) * 10;
				$data['createtime'] = time();
				$data['paytype'] = '支付宝';
				if ($this->model('Financedetail')->isExist($data['uid'], $data['ordernum']) === false) {
					$this->model('Financedetail')->insert($data);
					$this->model('UserMoney')->addMoney($data['uid'], $data['howmuch']);
					$this->model('consume')->insert(array(
						'userid' => $data['uid'],
						'itemid' => 0,
						'howmuch' => $data['howmuch'],
						'createtime' => time(),
						'sorpuserid' => 0,
						'consumetype' => 4
					));
					echo '1';die;
				}
			}
		}
		echo '0';
	}
	
	public function actionTest()
	{
		$id = $_GET['id'];
		$res = $this->model('test', 'test', 'id')->findByPk($id);
		$data = json_decode($res['post'], true);
		echo '<pre>';print_r($data);echo '</pre>';die;
		$notify_data = simplexml_load_string($data['notify_data']);
		echo '<pre>';print_r($notify_data);echo '</pre>';
		echo  $notify_data->out_trade_no . '|' . $notify_data->price;
		echo '<pre>';print_r(json_decode($res['post'], true));echo '</pre>';die;
	}
}